package com.zros.common.util.fastDFS;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Locale;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

/**
 * 配置文件读取工具类
 * @author bingo
 * @date 2015-09-01
 */
public class PropertiesUtil {
	
	private static Log log = LogFactory.getLog(PropertiesUtil.class);
	
	/**
	 * 
	 * @param vmName  启动应用是通过  -D设置的参数名称，如 CONFING_PATH、dubbo.protocol.port等
	 * @param classPathFileName 在classpath 下面的文件名，不带后缀，如 config.rocketmq
	 * @param fileName 文件全名，带后缀，如rocketmq.properties
	 * @return
	 */
	public static ResourceBundle getBundle(String vmName, String classPathFileName, String fileName){
		ResourceBundle resource = null;
		String configPath = System.getProperty(vmName);//获取vm动态参数
		if(configPath == null){//如果没有配置vm参数，根据classpath方式来获取
			resource = ResourceBundle.getBundle(classPathFileName, Locale.CHINA);
		}
		else{
			try{
				//根据vm参数配置的绝对路径获取
				File resourceFile = null;
				if(configPath.startsWith("file:")){
					configPath = configPath.substring("file:".length()) + "/" + fileName;
					resourceFile = new File(configPath);
				}
				else if(configPath.startsWith("classpath:")){
					configPath += "/" + fileName;
					resourceFile = ResourceUtils.getFile(configPath);
				}
				
				if(resourceFile != null){
					InputStream in = null;
					try{
						in = new FileInputStream(resourceFile);
						resource = new PropertyResourceBundle(in);
					}
					catch(Exception e){
						e.printStackTrace();
					}
					finally{
						if(in != null){
							in.close();
						}
					}
				}
			}
			catch(Exception e){
				log.error(e.getMessage(), e);
			}
		}
		return resource;
	}
	
	/**
	 * 获取配置文件值（优先获取vm参数的值）
	 * @param resource
	 * @param key
	 * @return
	 */
	public static String getString(ResourceBundle resource,String key){
		try{
			String vmKey = System.getProperty(key);//获取vm动态参数
			if(vmKey != null){
				return vmKey;//如果vm参数配置了该key，则优取该值
			}
			return resource.getString(key);
		}
		catch(Exception e){
		}
		return null;
	}
}
